<template>
  <div
    class="content-editable"
    ref="contentEditable"
    @input="onInput"
    @click="onClick"
    @blur="onBlur"
    @focus="onFocus"
    @keyUp="onKeyUp"
    @keyDown="onKeyDown"
    :contentEditable="!disabled"
    v-html="initialValue"
  />
</template>
<script>
export default {
  name: "ContentEditable",
  props: {
    disabled: Boolean,
    value: String
  },
  data() {
    return {
      initialValue: this.value,
      lastEditRange: null
    };
  },
  watch: {
    value(val) {
      console.log(val);
      this.initialValue = val;
    },
    initialValue(val) {
      this.$emit("input", val);
    }
  },
  methods: {
    setLastEditRange() {
      setTimeout(() => {
        const selection = window.getSelection();
        this.lastEditRange = selection.getRangeAt(0);
      });
    },
    insertContent() {
      const selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(this.lastEditRange);
    },
    getContent() {
      const el = this.$refs.contentEditable;
      if (!el) return;
      return el.innerHTML;
    },
    onInput() {
      const el = this.$refs.contentEditable;
      if (!el) return;
      const html = el.innerHTML;
      this.$emit("change", html, el);
      // this.initialValue = html;
      this.setLastEditRange();
    },
    onClick() {
      this.setLastEditRange();
    },

    onBlur() {
      this.$emit("blur");
    },
    onFocus() {
      this.$emit("focus");
      // this.setLastEditRange();
    },
    onKeyUp() {
      this.$emit("keyUp");
    },
    onKeyDown() {
      this.$emit("keyDown");
    }
  }
};
</script>
<style lang="less">
.content-editable {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 4px;
  font-size: 14px;
  box-sizing: content-box;
  outline: none;
}
</style>
